package com.xuetang.controller.api;

import com.xuetang.entity.CommunityComment;
import com.xuetang.entity.CommunityPost;
import com.xuetang.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 社区API控制器
 */
@RestController
@RequestMapping("/api/community")
public class CommunityController {

    @Autowired
    private CommunityService communityService;

    /**
     * 获取帖子列表
     */
    @GetMapping("/posts")
    public Map<String, Object> getPosts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer tagId,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 转换用户ID为Long型或为null
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            }

            Map<String, Object> data = communityService.listPosts(page, pageSize, tagId, userIdLong);

            result.put("code", 0);
            result.put("message", "获取成功");
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "获取失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/posts/{id}")
    public Map<String, Object> getPostDetail(
            @PathVariable Long id,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 转换用户ID为Long型或为null
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            }

            CommunityPost post = communityService.getPostDetail(id, userIdLong);

            if (post != null) {
                result.put("code", 0);
                result.put("message", "获取成功");
                result.put("data", post);
            } else {
                result.put("code", 404);
                result.put("message", "帖子不存在");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "获取失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 发布帖子
     */
    @PostMapping("/posts")
    public Map<String, Object> createPost(
            @RequestBody CommunityPost post,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            // 转换用户ID为Long型或为null
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            boolean success = communityService.createPost(post, userIdLong);

            if (success) {
                result.put("code", 0);
                result.put("message", "发布成功");
                result.put("data", post);
            } else {
                result.put("code", 1);
                result.put("message", "发布失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "发布失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 发表评论
     */
    @PostMapping("/posts/{postId}/comments")
    public Map<String, Object> addComment(
            @PathVariable Long postId,
            @RequestBody CommunityComment comment,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            // 转换用户ID为Long型或为null
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            comment.setPostId(postId);
            CommunityComment savedComment = communityService.addComment(comment, userIdLong);

            if (savedComment != null) {
                result.put("code", 0);
                result.put("message", "评论成功");
                result.put("data", savedComment);
            } else {
                result.put("code", 1);
                result.put("message", "评论失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "评论失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 点赞/取消点赞帖子
     */
    @PutMapping("/posts/{id}/like")
    public Map<String, Object> likePost(
            @PathVariable Long id,
            @RequestBody Map<String, Boolean> body,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            Boolean isLike = body.get("isLike");

            if (isLike == null) {
                result.put("code", 400);
                result.put("message", "参数错误，缺少isLike字段");
                return result;
            }

            // 转换用户ID为Long型
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            boolean success = communityService.likePost(id, userIdLong, isLike);

            if (success) {
                result.put("code", 0);
                result.put("message", isLike ? "点赞成功" : "取消点赞成功");
            } else {
                result.put("code", 1);
                result.put("message", "操作失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "操作失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 点赞/取消点赞评论
     */
    @PutMapping("/comments/{id}/like")
    public Map<String, Object> likeComment(
            @PathVariable Long id,
            @RequestBody Map<String, Boolean> body,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            Boolean isLike = body.get("isLike");

            if (isLike == null) {
                result.put("code", 400);
                result.put("message", "参数错误，缺少isLike字段");
                return result;
            }

            // 转换用户ID为Long型
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            boolean success = communityService.likeComment(id, userIdLong, isLike);

            if (success) {
                result.put("code", 0);
                result.put("message", isLike ? "点赞成功" : "取消点赞成功");
            } else {
                result.put("code", 1);
                result.put("message", "操作失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "操作失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/posts/{id}")
    public Map<String, Object> deletePost(
            @PathVariable Long id,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            // 转换用户ID为Long型
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            boolean success = communityService.deletePost(id);

            if (success) {
                result.put("code", 0);
                result.put("message", "删除成功");
            } else {
                result.put("code", 1);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "删除失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/comments/{id}")
    public Map<String, Object> deleteComment(
            @PathVariable Long id,
            @RequestHeader(value = "X-User-ID", required = false) String userId) {
        Map<String, Object> result = new HashMap<>();

        if (userId == null) {
            result.put("code", 401);
            result.put("message", "请先登录");
            return result;
        }

        try {
            // 转换用户ID为Long型
            Long userIdLong = null;
            if (userId != null && userId.matches("\\d+")) {
                userIdLong = Long.parseLong(userId);
            } else {
                // 对于微信小程序，可能使用字符串ID，这里直接生成一个唯一的数字ID
                userIdLong = Math.abs(userId.hashCode() % 1000000L);
            }

            boolean success = communityService.deleteComment(id);

            if (success) {
                result.put("code", 0);
                result.put("message", "删除成功");
            } else {
                result.put("code", 1);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "删除失败：" + e.getMessage());
        }

        return result;
    }
}